<?php
/**
 * 订单管理：发货需求
 * User: bgl
 * Date: 2022/7/27 14:09
 * IDE： PhpStorm
 */

namespace App\Admin\Controllers\CustomerDelivery;

use App\Admin\Ajax\CustomerDelivery\DeliveryDemandAjax;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Layout\Content;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Request;

class DeliveryDemandController extends AdminController
{
    protected $title = '客户订单';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'order_no' => null,
        //'status' => null,
        'sku' => null,
        'plat_id' => null,
    ];

    protected function grid()
    {
        $areaId = CustomerOrder::getSysAreaOutId();
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['order_no'] = $this->filters['order_no'];
        //$filtersBlade['status'] = getOptions(CustomerOrderDetails::$_status, $this->filters['status']);
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['plat_id'] = getOptions(SysPlat::options(), $this->filters['plat_id']);

        return view('customer-delivery.delivery-demand.index', compact('paginator','action','filtersBlade','areaId'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){

        $query = CustomerOrder::query()->orderBy('order_at', 'DESC')->orderBy('id', 'DESC');
        $query->whereHas('detail', function ($query){
            $query->whereIn('status',[
                CustomerOrderDetails::ORDER_DELIVERY_NO, //未发货
                CustomerOrderDetails::ORDER_DELIVERY_PART //部分发货
            ]);
        });
        foreach ($filters as $field => $filter){
            if($field == 'plat_id'){
                if (isset($filter)) {
                    $query->where('plat_id', $filter);
                }
            }
            if(!$filter)continue;

            if($field == 'start_date'){
                $query->where('order_at','>=',$filter.' 00:00:00');
            }
            if($field == 'end_date'){
                $query->where('order_at','<=',$filter.' 23:59:59');
            }
            if($field == 'sku'){
                $query->whereHas('detail.sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if(in_array($field,['order_no'])){
                $query->where($field,$filter);
            }
        }

        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new DeliveryDemandAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');

        $modal = new DeliveryDemandAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    public function edit($id, Content $content)
    {
        $outOrder = CustomerOrder::query()->findOrFail($id);
        $detailCount = $outOrder->detail->count();
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body(view('customer-delivery.delivery-demand-edit.index', compact('id','outOrder','detailCount')));
    }

    public function update($id){
        try{
            list($class,$name) = explode('-',Request::get('name'));
            $value = Request::get('value');
            if($name == 'order_num' && $value <= 0)return response()->json(['status' => false, 'message' => '下单数量必须为正整数']);
            $model = (CustomerOrder::$_class[$class])::query()->find($id);
            $model->{$name} = $value;
            if(!$model->save()){
                return response()->json(['status' => false, 'message' => '操作失败']);
            }else{
                return response()->json(['status' => true, 'message' => '操作成功']);
            }
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    public function create(Content $content){

        return $content
            ->title($this->title())
            ->description($this->description['create'] ?? trans('admin.create'))
            ->body(view('customer-delivery.delivery-demand-create.index'));
    }
}
